package xyz.example.securegeyserext.config

import org.yaml.snakeyaml.Yaml
import java.io.File
import java.io.FileInputStream
import java.io.FileWriter
import java.nio.file.Path

class ConfigManager(private val dataFolder: Path) {
    
    private val configFile = dataFolder.resolve("config.yml").toFile()
    private var configData: Map<String, Any> = emptyMap()
    
    companion object {
        const val AES_KEY = "aes-key"
        const val DEBUG = "debug"
        const val MAX_MESSAGE_LENGTH = "max-message-length"
        
        // 默认配置值
        private val defaults = mapOf(
            AES_KEY to "AAAAAAAAAAAAAAAAAAAAAA==",
            DEBUG to false,
            MAX_MESSAGE_LENGTH to 512
        )
    }
    
    fun load(): Boolean {
        return try {
            if (!configFile.exists()) {
                createDefaultConfig()
            }
            
            val yaml = Yaml()
            configData = yaml.load(FileInputStream(configFile)) ?: emptyMap()
            true
        } catch (ex: Exception) {
            ex.printStackTrace()
            false
        }
    }
    
    fun getString(key: String, defaultValue: String = ""): String {
        return configData[key]?.toString() ?: defaultValue
    }
    
    fun getBoolean(key: String, defaultValue: Boolean = false): Boolean {
        return when (val value = configData[key]) {
            is Boolean -> value
            is String -> value.lowercase() in listOf("true", "yes", "1")
            else -> defaultValue
        }
    }
    
    fun getInt(key: String, defaultValue: Int = 0): Int {
        return when (val value = configData[key]) {
            is Number -> value.toInt()
            is String -> value.toIntOrNull() ?: defaultValue
            else -> defaultValue
        }
    }
    
    private fun createDefaultConfig() {
        configFile.parentFile.mkdirs()
        
        val content = buildString {
            appendLine("# SecureBridgeExt Configuration File")
            appendLine("# ")
            appendLine("# aes-key: Base64 encoded AES-256 key for encryption/decryption")
            appendLine("# Make sure this matches the key configured in your server-side plugin")
            appendLine("aes-key: \"${defaults[AES_KEY]}\"")
            appendLine()
            appendLine("# Enable debug logging")
            appendLine("debug: ${defaults[DEBUG]}")
            appendLine()
            appendLine("# Maximum message length (in characters)")
            appendLine("max-message-length: ${defaults[MAX_MESSAGE_LENGTH]}")
        }
        
        FileWriter(configFile).use { it.write(content) }
    }
} 